from urllib.parse import quote

from langchain_core.runnables import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
# 引入redis的聊天记录
from langchain_community.chat_message_histories import RedisChatMessageHistory
import os



#获取redis的密码
password_encoded = quote(os.environ["REDIS_PASSWORD"])

# 定义redis的连接信息
redis_url = f"redis://:{password_encoded}@localhost:6379/0"

# 定义模型
llm = ChatOpenAI(model_name="deepseek-chat", api_key=os.environ["DEEPSEEK_API_KEY"],base_url=os.environ["DEEPSEEK_BASE_URL"])

# 定义提示词模板
prompt_template = ChatPromptTemplate.from_messages([
    ('system','你是一个乐于助人的助手，请尽你所能回答问题'),
    MessagesPlaceholder(variable_name="history_msg"), # 获取用户的聊天记录  variable_name 为 RunnableWithMessageHistory中的input_messages_key
    ('human',"{input_msg}")
])

# 创建一个runable
chain = prompt_template | llm

"""
获取聊天记录
"""
def get_chat_history(session_id):
    return RedisChatMessageHistory(session_id, redis_url)

#创建一个带聊天记录的runable
do_message = RunnableWithMessageHistory(
    chain,
    get_chat_history,
    input_messages_key="input_msg", # 自定义输入的聊天记录的key
    history_messages_key="history_msg" # 对应的MessagesPlaceholder中的variable_name 历史聊天记录
)

config = {'configurable':{'session_id':'boss'}}

while True:
    print("-" * 50)
    question = input("请输入你的问题:")
    resp = do_message.invoke({"input_msg":question},config=config)
    print("*" * 10)
    print("回答:",resp.content)
    print("*" * 10)
    # 判断是否继续聊天
    chat_state = input("是否还继续聊天(1-是/0-否)?")
    while chat_state not in ["1","0"]:
        chat_state = input("请只输入Y或者N")
    if chat_state == "0":
        break